#!/bin/bash

set -ex

# 配置参数
INSTALL_PREFIX="./out"      # 安装目录
BUILD_DIR="./build"         # 构建目录
PORT=50051                  # 服务端端口
CLIENT_EXE="${INSTALL_PREFIX}/bin/client"
BUILD_TYPE="MinSizeRel"

IOS_PROJECT_DIR="./build-ios"   # iOS Xcode工程目录
DEVICE_UDID=""
IPROXY_PID=0

# 清理函数
cleanup() {
    # 停止端口转发
    if [ ${IPROXY_PID} -ne 0 ]; then
        echo "Stopping port forwarding (PID: ${IPROXY_PID})..."
        kill ${IPROXY_PID} > /dev/null 2>&1 || true
    fi

    echo "Cleanup complete."
}

# 捕获中断信号
trap cleanup SIGINT SIGTERM

# 检查依赖工具
check_dependencies() {
    # 检查Linux构建依赖
    if ! command -v cmake &> /dev/null || ! command -v make &> /dev/null; then
        echo "Error: CMake and Make are required for Linux build"
        exit 1
    fi

    # 检查iOS设备工具
    if [ "$1" = "run" ] && (! command -v iproxy &> /dev/null); then
        echo "Error: Required iOS tools not found. Install with:"
        echo "brew install libimobiledevice"
        exit 1
    fi
}

# 检测连接的iOS设备
detect_ios_device() {
    echo "Detecting iOS devices..."
    local devices
    devices=$(idevice_id -l)

    if [ -z "${devices}" ]; then
        echo "Error: No connected iOS devices found"
        exit 1
    fi

    # 选择第一个连接的设备
    DEVICE_UDID=$(echo "${devices}" | head -n 1)
    echo "Using device: ${DEVICE_UDID}"

    # 检查设备信任状态
    if ! ideviceinfo -u ${DEVICE_UDID} &> /dev/null; then
        echo "Error: Device is not trusted. Please unlock your device and trust this computer."
        exit 1
    fi
}

# 构建Linux版本并生成Xcode工程
build() {
    echo "Building project..."

    # 运行CMake配置
    cmake -S . -B build -G "Ninja"                  \
        -DCMAKE_INSTALL_PREFIX=${INSTALL_PREFIX}    \
        -DCMAKE_BUILD_TYPE=${BUILD_TYPE}            \
        -DCMAKE_EXPORT_COMPILE_COMMANDS=TRUE        \
        -DCMAKE_C_COMPILER=clang                    \
        -DCMAKE_CXX_COMPILER=clang++

    # 构建项目
    cmake --build build --config ${BUILD_TYPE} -j$(nproc)

    # 安装到指定目录
    echo "Installing to ${INSTALL_PREFIX}..."
    cmake --install build --config ${BUILD_TYPE}

    # 生成Xcode工程
    cd platforms/ios
    cmake -S . -G Xcode -B ${IOS_PROJECT_DIR}


    echo "Generated Xcode project at $(cd ${IOS_PROJECT_DIR} && pwd)"
    echo "To open the project, run:"
    echo "open $(cd ${IOS_PROJECT_DIR} && pwd)/grpcapp.xcodeproj"
}

# 运行端口转发并启动应用
run() {
    echo "Running gRPC server and client..."

    # 检测设备
    detect_ios_device

    # 设置端口转发
    echo "Starting port forwarding (local:${PORT} <-> device:${PORT})..."
    iproxy -u ${DEVICE_UDID} ${PORT} ${PORT} &
    IPROXY_PID=$!
    sleep 2  # 等待端口转发启动

    # 检查端口是否可用
    if ! nc -z localhost ${PORT}; then
        echo "Error: Port forwarding failed to start"
        cleanup
        exit 1
    fi

    echo "=== Server is ready ==="
    echo "Server running on device ${DEVICE_UDID}, accessible at localhost:${PORT}"
    echo "Press Ctrl+C to stop..."

    echo "Connecting to server at localhost:${PORT}..."
    ${CLIENT_EXE} localhost ${PORT}

    # 客户端退出后等待用户输入再关闭服务端
    echo -e "\nClient exited."
}

# 显示帮助信息
show_help() {
    echo "Usage: $0 [COMMAND]"
    echo "Commands:"
    echo "  build    Build Linux version and generate Xcode project for iOS"
    echo "  run      Start port forwarding and launch app on connected iOS device"
    echo "  help     Show this help message"
}

# 主函数
main() {
    if [ $# -eq 0 ]; then
        show_help
        exit 1
    fi

    check_dependencies "$1"

    case "$1" in
        build)
            build
            ;;
        run)
            run
            ;;
        help)
            show_help
            ;;
        *)
            echo "Error: Unknown command '$1'"
            show_help
            exit 1
            ;;
    esac
}

# 启动主流程
main "$@"